package com.hello.controller;


import com.hello.constant.JwtClaimsConstant;
import com.hello.dto.UserDTO;
import com.hello.dto.UserLoginDTO;
import com.hello.dto.UserRegisterDTO;
import com.hello.entity.Follow;
import com.hello.properties.JwtProperties;
import com.hello.result.Result;
import com.hello.service.IFollowService;
import com.hello.service.IPLikesService;
import com.hello.service.IPostService;
import com.hello.service.IUserService;
import com.hello.utils.JwtUtil;
import com.hello.vo.FollowVO;
import com.hello.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.security.auth.login.AccountNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/user")
@Slf4j
@Api(tags = "用户相关接口")
public class UserController {

    @Resource
    private IUserService userService;
    @Resource
    private IFollowService followService;
    @Resource
    private IPostService postService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private IPLikesService plikesService;

    /**
     * 用户分页查询
     * @return
     */
    @GetMapping("/queryUserList")
    @ApiOperation(value = "用户分页查询")
    public Result queryUserList(){
        log.info("用户分页查询");
        List<UserDTO> userDTOS= userService.queryUserList( );
        return Result.success(userDTOS);
    }

    /**
     * 新增员工
     * @param userRegisterDTO
     * @return
     */
    @PostMapping("/addUser")
    @ApiOperation(value = "注册")
    public Result addUser(@RequestBody UserRegisterDTO userRegisterDTO){
        log.info("新增用户:{}",userRegisterDTO);
        System.out.println("当前线程id:" + Thread.currentThread().getId());
        UserDTO userDTO = new UserDTO();
        userDTO.setUsername(userRegisterDTO.getUserName());
        userDTO.setPassword(userRegisterDTO.getPassword());
        userDTO.setHeadshotUrl("null");
        userDTO.setPetNum(0);

        userService.addUser(userDTO);
        Long userid = userService.searchByName(userRegisterDTO.getUserName()).getUserId();
        return Result.success(userid);
    }
    /**
     * 删除用户
     * @param user_id
     * @return
     */
    @PostMapping("/deleteUser/{user_id}")
    @ApiOperation(value = "删除用户")
    public Result deleteUser(@PathVariable Long user_id){
        log.info(("删除用户"));
        boolean result = userService.delUserById(user_id);
        if(result) return  Result.success();
        else return Result.error("删除用户失败");
    }
    /**
     * 更新用户信息
     * @param userDTO
     * @return
     */
    @PostMapping("/updateUser")
    @ApiOperation(value = "更新用户")
    public Result updateUser(@RequestBody UserDTO userDTO){
        log.info("更新用户");
        boolean result =  userService.updateUser(userDTO);
        if(result) return Result.success();
        else return Result.error("更新用户信息失败");
    }

    /**
     * 根据id查询员工
     * @param user_id
     * @return
     */
    @PostMapping("/getById/{user_id}")
    @ApiOperation(value = "用id查询用户")
    public Result<UserDTO> getById(@PathVariable Long user_id){
        log.info("根据id查询用户");
        UserDTO userDTO = userService.searchById(user_id);
        return Result.success(userDTO);
    }
    /**
     * 登录
     * @param userLoginDTO
     * @return
     * @throws AccountNotFoundException
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public  Result<UserDTO> login(@RequestBody UserLoginDTO userLoginDTO) throws AccountNotFoundException{
        log.info("用户登录：{}",userLoginDTO);
        Integer code = userService.login(userLoginDTO);
        Map<String,Object> claims = new HashMap<>();
        if(code == 0) {
            claims.put(JwtClaimsConstant.EMP_ID, userLoginDTO.getUsername());
            String token = JwtUtil.createJWT(
                    jwtProperties.getAdminSecretKey(),
                    jwtProperties.getAdminTtl(),
                    claims);
            UserLoginVO userLoginVO = UserLoginVO.builder()
                    .userId(userService.searchByName(userLoginDTO.getUsername()).getUserId())
                    .userName(userLoginDTO.getUsername())
                    .token(token)
                    .build();
            UserDTO userDTO = userService.searchByName(userLoginDTO.getUsername());
            return Result.success(userDTO);
        }
        else if(code == 1){
            return Result.error("AccountNotFound");
        }
        else if(code == 2){
            return Result.error("PasswordError");
        }
        return Result.error("error");
    }


    @PostMapping("/getFollowing/{user_id}")
    @ApiOperation(("我的关注"))
    public  Result getFollowing(@PathVariable Long user_id){
        log.info("我的关注");
        List<Follow> follows = followService.getFollowing(user_id);
        List<FollowVO> list  = new ArrayList<>();
        for(Follow follow:follows){
            UserDTO userDTO  = userService.searchById(follow.getFollowingId());
            //Post post = postService.getPostDetail(pLike.getHostId(),pLike.getPostOrder());
            FollowVO followVO = FollowVO.builder()
                    .hostName(userDTO.getUsername())
                    .headshotUrl(userDTO.getHeadshotUrl())
//                    .text(post.getText())
//                    .postTime(post.getPostTime())
                    .build();
            list.add(followVO);
        }
        return Result.success(list);
    }


}
